// import Cookies from 'js-cookie'
import qs from 'qs'
import axios from 'axios'
import store from '@/store'

const TokenKey = 'CRMPC_TOKEN'
const NewTokenKey = 'NEWCRMPC_TOKEN'

export function getToken() {
 
  return localStorage.getItem(TokenKey)
}
export function getNewToken() {
  
  return localStorage.getItem(NewTokenKey)
}

export async function setToken(token) {
  const result = localStorage.setItem(TokenKey, token)
  await store.dispatch('app/applicationConfiguration')
  return result
}

export async function setNewToken(token) {
  const result = localStorage.setItem(NewTokenKey, token)
 
  return result
}
export async function removeToken() {
  const result = localStorage.removeItem(TokenKey)
  await store.dispatch('app/applicationConfiguration')
  return result
}

export async function removeNewToken() {
  const result = localStorage.removeItem(NewTokenKey)

  return result
}


export function getTokenByRequest({ username, password }) {
  return new Promise((resolve, reject) => {
    const data = {
      username,
      password,
      grant_type: 'password',
      client_id: public_config.VUE_APP_CLIENT_ID,
      client_secret: public_config.VUE_APP_CLIENT_SECRET
    }
    const serv = axios.create({
      timeout: 5000 // request timeout
    })
    serv({
      url: public_config.auth_api + '/connect/token',
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'post',
      data: qs.stringify(data)
    }).then(res => {
      console.log('执行了一次token请求')
      if (res.status === 200) {
        // commit("SET_TOKEN", res.data.access_token)
        setToken(res.data.access_token)
        resolve(res.data.access_token)
      } else {
        reject('Error')
      }
    }, err => {
      reject(err)
    })
  })
}
